import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { Formula, FormulaLibrary } from '../types';

export const useFormulaStore = defineStore('formula', () => {
    const currentFormula = ref<Formula>({
        id: '',
        title: '',
        content: '',
        latex: '',
        createdAt: 0,
        updatedAt: 0
    });

    const formulaLibrary = ref<FormulaLibrary>({
        name: '我的公式库',
        formulas: []
    });

    const createNewFormula = () => {
        const id = Date.now().toString();
        currentFormula.value = {
            id,
            title: `未命名公式_${id.slice(-4)}`,
            content: '',
            latex: '',
            createdAt: Date.now(),
            updatedAt: Date.now()
        };
    };

    const saveFormula = () => {
        const index = formulaLibrary.value.formulas.findIndex(
            f => f.id === currentFormula.value.id
        );

        if (index >= 0) {
            formulaLibrary.value.formulas[index] = { ...currentFormula.value };
        } else {
            formulaLibrary.value.formulas.push({ ...currentFormula.value });
        }

        currentFormula.value.updatedAt = Date.now();
    };

    const loadFormula = (id: string) => {
        const formula = formulaLibrary.value.formulas.find(f => f.id === id);
        if (formula) {
            currentFormula.value = { ...formula };
        }
    };

    const deleteFormula = (id: string) => {
        const index = formulaLibrary.value.formulas.findIndex(f => f.id === id);
        if (index >= 0) {
            formulaLibrary.value.formulas.splice(index, 1);
        }
    };

    return {
        currentFormula,
        formulaLibrary,
        createNewFormula,
        saveFormula,
        loadFormula,
        deleteFormula
    };
});
